<%@ page trimDirectiveWhitespaces="true" %>
<%@page import="com.jason.imagesnode.MyStringUtil" %>
<%@page import="com.jason.imagesnode.util.HttpUtils" %>
<%@page import="org.apache.commons.fileupload.FileItem" %>
<%@page import="org.apache.commons.fileupload.FileItemFactory" %>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory" %>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>
<%@ page import="org.apache.http.HttpResponse" %>
<%@ page import="org.apache.http.util.EntityUtils" %>
<%@ page import="org.json.JSONObject" %>
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ page import="java.io.File" %>
<%@ page import="java.io.InputStream" %>
<%@ page import="java.util.*" %>
<%@ page import="static org.apache.commons.codec.binary.Base64.encodeBase64" %>
<%@ page import="java.io.FileInputStream" %>

<%
    String sId = UUID.randomUUID().toString();
    String Sql = null;
    FileItemFactory factory = null;
    ServletFileUpload upload = null;
    List<FileItem> fileItems = null;
    Iterator<FileItem> iter = null;
    FileItem item = null;
    String ext = "txt";
    File file = null;
    String fileName = "";
    response.setHeader("Access-Control-Allow-Origin", "*");
    int number = 1;

    JSONObject obj = new JSONObject();
    obj.put("result", "Y");
    boolean flag = true;
    try {
        String postfixName = (String) request.getParameter("postfixName");// 服务器前缀
        if (MyStringUtil.isBlank(postfixName)) {
            postfixName = "";
        }

        request.setCharacterEncoding("UTF-8");
        factory = new DiskFileItemFactory();
        upload = new ServletFileUpload(factory);

        upload.setFileSizeMax(1024 * 1024 * 100);// 最大100M
        // 得到所有的表单域，它们目前都被当作FileItem
        fileItems = upload.parseRequest(request);
        iter = fileItems.iterator();
        //String basePath = Resources.getProperty("FileStore", Utils.getWebRootPath());
        String basePath = getServletContext().getRealPath("/");


        String filenames = "";// 文件名
        int i = 0;
        while (iter.hasNext()) {
            String filename = UUID.randomUUID().toString().replace("-", "");
            filename = MyStringUtil.getFileName(filename, postfixName);
            String filepath = MyStringUtil.getFilePath(filename);
            File f = new File(basePath + filepath);
            if (!f.exists()) {
                f.mkdirs();
            }

            item = (FileItem) iter.next();
            if (!item.isFormField()) {
                fileName = item.getName();
                String[] strs = fileName.split("\\.");
                ext = strs[strs.length - 1];
                ext = ext.toLowerCase();
                file = new File(basePath + filepath + "/" + filename + "." + ext);
                if (i++ > 0) {
                    filenames += ",";
                }
                filenames += filename + "." + ext;
                item.write(file);


                // 添加营销注册
                String APP_CODE = "71a4d0641cb444889c4c2e5790354bdd";   //阿里云市场app code
                String host = "https://dm-58.data.aliyun.com";
                String path = "/rest/160601/ocr/ocr_business_license.json";
                String method = "POST";
                //消息头
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Authorization", "APPCODE " + APP_CODE);
                //根据API的要求，定义相对应的Content-Type
                headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                Map<String, String> querys = new HashMap<String, String>();
                //内容数据类型，如：0，则表示BASE64编码；1，则表示图像文件URL链接

                //启用BASE64编码方式进行识别
                //内容数据类型是BASE64编码
                String imgBase64 = "";

                byte[] content = new byte[(int) file.length()];
                InputStream finputstream = new FileInputStream(file);
                finputstream.read(content);
                finputstream.close();
                imgBase64 = new String(encodeBase64(content));

                String bodys = "{\"image\":\"" + imgBase64 + "\"}";


                org.apache.http.HttpResponse responses = HttpUtils.doPost(host, path, method, headers, querys, bodys);
                //获取response的body
                String words = EntityUtils.toString(responses.getEntity());
                System.out.println(words);

                JSONObject object = new JSONObject(words);
                //统一社会信用代码
                String businesscode = object.get("reg_num").toString();
                //法定人代表
                String owner = object.get("person").toString();
                //营业范围
                String business = object.get("business").toString();

                obj.put("businesscode", businesscode);
                obj.put("owner", owner);
                obj.put("business",business);

            } else {
                String x = item.getFieldName();
                String value = item.getString();
                if ("sId".equals(x)) {
                    sId = value;
                } else if ("number".equals(x)) {
                    try {
                        number = Integer.parseInt(value);
                    } catch (Exception e) {
                    }
                }
            }
        }
        //System.out.println("basePath:" + basePath + "filepath" + filepath + "fileName: " + filename);
        //Utils.saveFile(filename, fileName, "-1", null, sId,number);
        obj.put("filename", filenames);
    } catch (Exception e) {
        obj.put("errMsg", e);
        obj.put("result", "N");
        e.printStackTrace();
    } finally {
        try {
            factory = null;
            upload = null;
            fileItems = null;
            iter = null;
            item = null;
        } catch (Exception e) {
        }
        //out.println("Access-Control-Allow-Origin:*\r\n");
        out.println(obj.toString());
    }
%>
